﻿Imports System.IO
Imports System.Web.UI
Imports System.Web.UI.WebControls

Namespace DotNetNuke.Modules.ActiveForums
    Partial Public Class af_uploader
        Inherits ForumBase
        Private PendingAttach As Integer = 0
        Public ContentId As Integer = -1
        Public AuthorId As Integer = -1
#Region "Event Handlers"
        Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            If Permissions.HasPerm(ForumInfo.Security.Attach, ForumUser.UserRoles) Or Permissions.HasPerm(ForumInfo.Security.ModEdit, ForumUser.UserRoles) Then
                btnUpload.ImageUrl = ImagePath & "/images/upload16.png"
                btnUpload.ObjectId = "btnUpload"
                btnUpload.Text = GetSharedResource("[RESX:Upload]")
                If Not cbAttach.IsCallback Then
                    BindAttach(String.Empty)
                    BindMyFiles()
                End If
            End If

        End Sub
        Private Sub cbAttach_Callback(ByVal sender As Object, ByVal e As Modules.ActiveForums.Controls.CallBackEventArgs) Handles cbAttach.Callback
            Dim attachIds As String = e.Parameters(1).ToString
            Select Case e.Parameters(0).ToLowerInvariant

                Case "delcont"
                    If IsNumeric(e.Parameters(2)) Then
                        Dim aid As Integer = CInt(e.Parameters(2))
                        Dim uid As Integer = -1
                        If IsNumeric(e.Parameters(3)) Then
                            uid = CInt(e.Parameters(3))
                        End If
                        If (uid = Me.UserId And Not Me.UserId = -1) Or Permissions.HasPerm(ForumInfo.Security.ModDelete, ForumUser.UserRoles) Or UserInfo.IsSuperUser Then
                            Dim adb As New Data.AttachController
                            adb.Attach_Delete(aid, ContentId)
                            'ac.Attach_Delete(aid, -1, uid)
                        End If

                    End If
                Case "thumb"
                    If IsNumeric(e.Parameters(2)) Then
                        Dim aid As Integer = CInt(e.Parameters(2))
                        Dim ac As New Data.AttachController
                        Dim uid As Integer = -1
                        If IsNumeric(e.Parameters(3)) Then
                            uid = CInt(e.Parameters(3))
                        End If
                        Dim ai As AttachInfo = ac.Attach_Get(aid, -1, uid, False)
                        If Not ai Is Nothing Then
                            Dim w As Integer = CInt(e.Parameters(4))
                            Dim h As Integer = CInt(e.Parameters(5))
                            Dim imgStream As New IO.MemoryStream
                            Dim fpath As String = String.Empty
                            Dim fileSize As Integer = 0
                            Dim tmpFilename As String = String.Empty
                            If Not ai.FileData Is Nothing Then
                                Dim bindata() As Byte
                                bindata = CType(ai.FileData, Byte())
                                Dim memStream As New IO.MemoryStream(bindata)
                                imgStream = CType(Images.CreateImageForDB(memStream, h, w), IO.MemoryStream)
                                fileSize = CInt(imgStream.Length)
                                tmpFilename = "thumb_" & ai.Filename
                            Else

                                fpath = Server.MapPath(PortalSettings.HomeDirectory & "activeforums_Attach/")
                                'fpath &= "thumb_" & ai.Filename
                                tmpFilename = "thumb_" & ai.Filename
                                Dim sFullFile As String = fpath & tmpFilename
                                Dim i As Integer = 0

                                While File.Exists(sFullFile)
                                    i += 1
                                    tmpFilename = i.ToString.PadLeft(3, CChar("0")) & "_thumb_" & ai.Filename
                                    sFullFile = fpath & tmpFilename
                                End While
                                File.Copy(fpath & ai.Filename, sFullFile)
                                Images.CreateImage(sFullFile, h, w)
                                fileSize = CInt(FileLen(sFullFile))
                            End If
                            Dim aiThumb As New AttachInfo
                            aiThumb.ContentId = -1
                            aiThumb.UserID = ai.UserID
                            aiThumb.Filename = tmpFilename
                            aiThumb.ContentType = "image/x-png"
                            aiThumb.FileSize = fileSize
                            If ForumInfo.AttachStore = AttachStores.DATABASE Then
                                aiThumb.FileData = imgStream.ToArray
                                'File.Delete(fpath & "thumb_" & ai.Filename)
                            End If
                            aiThumb.ParentAttachId = aid
                            Dim thumbId As Integer = ac.Attach_Save(aiThumb)
                            attachIds &= thumbId.ToString & ";"
                            BindMyFiles()
                            If CBool(e.Parameters(4)) Then
                                Dim strHost As String = DotNetNuke.Common.AddHTTP(DotNetNuke.Common.GetDomainName(Request)) & "/"
                                Dim s As String = "<script type=""text/javascript"">"
                                Dim sInsert As String = String.Empty
                                If ForumInfo.AllowHTML And ForumInfo.EditorType <> EditorTypes.TEXTBOX Then
                                    sInsert = "<a href=""" & strHost & "DesktopModules/ActiveForums/viewer.aspx?portalid=" & PortalId & "&moduleid=" & ModuleId & "&attachid=" & aid & """ target=""_blank""><img src=" & strHost & "DesktopModules/ActiveForums/viewer.aspx?portalid=" & PortalId & "&moduleid=" & ModuleId & "&attachid=" & thumbId & " border=0 /></a>"
                                Else
                                    sInsert = "[THUMBNAIL:" & thumbId.ToString & ":" & aid & "]"
                                End If

                                s &= "amaf_insertHTML('" & sInsert & "');"
                                s &= "</script>"
                                Dim litScript As New LiteralControl
                                litScript.Text = s
                                plhAttach.Controls.Add(litScript)

                            End If


                        End If

                    End If
                Case "inline"
                    If IsNumeric(e.Parameters(2)) Then
                        Dim aid As Integer = CInt(e.Parameters(2))
                        Dim ac As New Data.AttachController
                        Dim uid As Integer = -1
                        If IsNumeric(e.Parameters(3)) Then
                            uid = CInt(e.Parameters(3))
                        End If
                        Dim ai As AttachInfo = ac.Attach_Get(aid, -1, uid, False)
                        If Not ai Is Nothing Then
                            Dim opt As Integer = CInt(e.Parameters(4))
                            If opt = 0 Then
                                ai.DisplayInline = True
                                ai.AllowDownload = False
                            Else
                                If ai.AllowDownload Then
                                    ai.DisplayInline = True
                                    ai.AllowDownload = False
                                Else
                                    ai.DisplayInline = False
                                    ai.AllowDownload = True
                                End If
                            End If


                            ac.Attach_Save(ai)
                        End If
                    End If
            End Select

            BindAttach(attachIds)
            Dim stringWriter As System.IO.StringWriter = New System.IO.StringWriter()
            Dim htmlWriter As HtmlTextWriter = New HtmlTextWriter(stringWriter)
            plhAttach.RenderControl(htmlWriter)
            Dim html As String = stringWriter.GetStringBuilder().ToString
            html = Utilities.LocalizeControl(html)
            Dim lit As New LiteralControl
            lit.Text = html
            lit.RenderControl(e.Output)
        End Sub
        Private Sub cbMyFiles_Callback(ByVal sender As Object, ByVal e As Modules.ActiveForums.Controls.CallBackEventArgs) Handles cbMyFiles.Callback
            Dim attachIds As String = e.Parameters(1).ToString
            Select Case e.Parameters(0).ToLowerInvariant

                Case "del"
                    If IsNumeric(e.Parameters(2)) Then
                        Dim aid As Integer = CInt(e.Parameters(2))
                        Dim ac As New Data.AttachController
                        Dim uid As Integer = -1
                        If IsNumeric(e.Parameters(3)) Then
                            uid = CInt(e.Parameters(3))
                        End If
                        If (uid = Me.UserId And Not Me.UserId = -1) Or Permissions.HasPerm(ForumInfo.Security.ModDelete, ForumUser.UserRoles) Or UserInfo.IsSuperUser Then
                            ac.Attach_Delete(aid, -1, uid)
                        End If

                    End If


            End Select
            PendingAttach = 0
            plhMyFiles.Controls.Clear()
            BindMyFiles()
            Dim stringWriter As System.IO.StringWriter = New System.IO.StringWriter()
            Dim htmlWriter As HtmlTextWriter = New HtmlTextWriter(stringWriter)

            plhMyFiles.RenderControl(htmlWriter)
            Dim html As String = stringWriter.GetStringBuilder().ToString
            html = Utilities.LocalizeControl(html)
            Dim lit As New LiteralControl
            lit.Text = html
            lit.RenderControl(e.Output)
        End Sub
#End Region
#Region "Private Methods"
        Private Function BuildAttachGrid(ByVal AttachIds As String) As String
            Return BuildAttachGrid(AuthorId, AttachIds, -1, -1, String.Empty, String.Empty)
        End Function
        Private Function BuildAttachGrid(ByVal Uid As Integer, ByVal AttachIds As String, ByVal RowIndex As Integer, ByVal MaxRows As Integer, ByVal SortColumn As String, ByVal Sort As String) As String
            Dim mode As Integer = 0
            If RowIndex > -1 Then
                mode = 1
            End If
            PendingAttach = 0
            Dim sOut As String = String.Empty
            Dim ac As New Data.AttachController
            Dim i As Integer = 0
            Dim strHost As String = DotNetNuke.Common.AddHTTP(DotNetNuke.Common.GetDomainName(Request)) & "/"
            Dim al As List(Of AttachInfo) = Nothing
            If RowIndex = -1 Then
                al = ac.Attach_ListAttachFiles(Uid, AttachIds)
            Else
                al = ac.Attach_ListMyFiles(Uid, RowIndex, MaxRows, SortColumn, Sort)
            End If
            For Each ai As AttachInfo In al
                PendingAttach += 1
                Dim insertHTML As String = String.Empty
                Dim insertThumb As String = String.Empty
                Dim toggleInline As String = String.Empty
                Dim deleteAttach As String = Page.ResolveUrl("~/DesktopModules/ActiveForums/Images/delete12.png")
                If mode = 1 Then
                    deleteAttach = "<img src=""" & deleteAttach & """ style=""cursor:pointer;"" onclick=""af_delAttach(" & ai.AttachID.ToString & "," & ai.UserID.ToString & ");"" />"
                Else
                    deleteAttach = "<img src=""" & deleteAttach & """ style=""cursor:pointer;"" onclick=""af_delContAttach(" & ai.AttachID.ToString & "," & ai.UserID.ToString & ");"" />"
                End If
                If ai.Filename.ToLowerInvariant.Contains(".jpg") Or ai.Filename.ToLowerInvariant.Contains(".bmp") Or ai.Filename.ToLowerInvariant.Contains(".gif") Or ai.Filename.ToLowerInvariant.Contains(".png") Or ai.Filename.ToLowerInvariant.Contains(".jpeg") Then
                    Dim w As Integer = 0
                    Dim h As Integer = 0
                    Dim fpath As String
                    fpath = Server.MapPath(PortalSettings.HomeDirectory & "activeforums_Attach/")
                    fpath &= ai.Filename
                    Dim bindata() As Byte
                    bindata = CType(ai.FileData, Byte())
                    If Not bindata Is Nothing Then
                        Dim memStream As New IO.MemoryStream(bindata)
                        Try
                            Dim g As System.Drawing.Image = System.Drawing.Image.FromStream(memStream)
                            If Not g Is Nothing Then
                                w = g.Width
                                h = g.Height
                            End If
                        Catch ex As Exception

                        End Try
                    Else

                        Try
                            Dim g As System.Drawing.Image = System.Drawing.Image.FromFile(fpath)
                            If Not g Is Nothing Then
                                w = g.Width
                                h = g.Height
                            End If
                        Catch ex As Exception

                        End Try


                    End If

                    If mode = 0 Then
                        Dim sInsert As String = String.Empty
                        Dim sClose As String = String.Empty
                        If ai.ParentAttachId > 0 Then
                            sInsert = "<a href=""" & Page.ResolveUrl("~/DesktopModules/ActiveForums/viewer.aspx") & "?portalid=" & PortalId & "&moduleid=" & ModuleId & "&attachid=" & ai.ParentAttachId & """ target=""_blank"">"
                            sClose = "</a>"
                        End If
                        If ai.FileData Is Nothing Then
                            Dim vpath As String
                            vpath = PortalSettings.HomeDirectory & "activeforums_Attach/"
                            sInsert &= "<img src=""" & vpath & ai.Filename & """ border=""0"" class=""afimg"" />"
                        Else
                            sInsert &= "<img src=" & Page.ResolveUrl("~/DesktopModules/ActiveForums/viewer.aspx") & "?portalid=" & PortalId & "&moduleid=" & ModuleId & "&attachid=" & ai.AttachID & " border=0 class=""afimg"" />"
                        End If

                        sInsert &= sClose
                        If ForumInfo.AllowHTML And ForumInfo.EditorType <> EditorTypes.TEXTBOX Then
                            insertHTML = "<a href=""javascript:amaf_insertHTML('" & Server.HtmlEncode(sInsert) & "');amaf_toggleInline(" & ai.AttachID & "," & ai.UserID & ",0);""><img border=""0"" src=""" & Page.ResolveUrl("~/DesktopModules/ActiveForums/Images/image_insert.png") & """ style=""cursor:pointer;"" alt=""[RESX:InsertImage]"" /></a>"
                        Else
                            If ai.ParentAttachId > 0 Then
                                insertHTML = "<a href=""javascript:amaf_insertHTML('[THUMBNAIL:" & ai.AttachID & ":" & ai.ParentAttachId & "]');amaf_toggleInline(" & ai.AttachID & "," & ai.UserID & ",0);""><img border=""0"" src=""" & Page.ResolveUrl("~/DesktopModules/ActiveForums/Images/image_insert.png") & """ style=""cursor:pointer;"" alt=""[RESX:InsertImage]"" /></a>"
                            Else
                                insertHTML = "<a href=""javascript:amaf_insertHTML('[IMAGE:" & ai.AttachID & "]');amaf_toggleInline(" & ai.AttachID & "," & ai.UserID & ",0);""><img border=""0"" src=""" & Page.ResolveUrl("~/DesktopModules/ActiveForums/Images/image_insert.png") & """ style=""cursor:pointer;"" alt=""[RESX:InsertImage]"" /></a>"
                            End If

                        End If
                        insertThumb = "<a href=""javascript:amaf_insertThumbnail(" & ai.AttachID & "," & ai.UserID & "," & w & "," & h & ");""><img src=""" & Page.ResolveUrl("~/DesktopModules/ActiveForums/Images/image_thumb.png") & """ style=""cursor:pointer;"" alt=""[RESX:CreateThumbnail]"" border=""0"" /></a>"
                        If ai.AllowDownload Then
                            toggleInline = "<a href=""javascript:amaf_toggleInline(" & ai.AttachID & "," & ai.UserID & ",1);""><img border=""0"" src=""" & Page.ResolveUrl("~/DesktopModules/ActiveForums/Images/checkbox.png") & """ style=""cursor:pointer;"" alt=""[RESX:AllowDownload]"" /></a>"
                        Else
                            toggleInline = "<a href=""javascript:amaf_toggleInline(" & ai.AttachID & "," & ai.UserID & ",1);""><img border=""0"" src=""" & Page.ResolveUrl("~/DesktopModules/ActiveForums/Images/checkbox_unchecked.png") & """ style=""cursor:pointer;"" alt=""[RESX:AllowDownload]"" /></a>"
                        End If
                    Else
                        toggleInline = "<a href=""javascript:amaf_addAttach(" & ai.AttachID & "," & ai.UserID & ");""><img border=""0"" src=""" & Page.ResolveUrl("~/DesktopModules/ActiveForums/Images/add.png") & """ style=""cursor:pointer;"" alt=""[RESX:AddAttach]"" /></a>"
                    End If
                Else
                    If mode = 1 Then
                        toggleInline = "<a href=""javascript:amaf_addAttach(" & ai.AttachID & "," & ai.UserID & ");""><img border=""0"" src=""" & Page.ResolveUrl("~/DesktopModules/ActiveForums/Images/add.png") & """ style=""cursor:pointer;"" alt=""[RESX:AddAttach]"" /></a>"
                    End If
                End If
                Dim rClass As String = "afrow"
                If i Mod 2 = 0 Then
                    rClass &= " afhighlight"
                End If
                sOut &= "<tr onmouseout=""this.className='" & rClass & "';"" class=""" & rClass & """><td>" & ai.Filename & "</td><td>" & Utilities.FormatFileSize(ai.FileSize) & "</td><td align=""center"">" & insertThumb & "</td><td align=""center"">" & insertHTML & "</td><td align=""center"">" & toggleInline & "</td><td align=""center"">" & deleteAttach & "</td></tr>"
                i += 1
            Next
            Dim tbl As String = String.Empty
            Dim createThumbHD As String = String.Empty
            Dim insertImageHD As String = String.Empty
            Dim downloadHD As String = String.Empty
            If sOut <> "" Then

                If mode = 0 Then
                    createThumbHD = "[RESX:CreateThumbnail]"
                    insertImageHD = "[RESX:InsertImage]"
                    downloadHD = "[RESX:AllowDownload]"
                Else
                    downloadHD = "[RESX:AddAttach]"
                End If
                tbl = "<table cellpadding=""0"" cellspacing=""0"" width=""95%""><tr><td class=""afattachhead"">[RESX:FileName]</td><td class=""afattachhead"">[RESX:FileSize]</td><td class=""afattachhead"" align=""center"">" & createThumbHD & "</td><td class=""afattachhead"" align=""center"">" & insertImageHD & "</td><td class=""afattachhead"" align=""center"">" & downloadHD
                tbl &= "</td><td class=""afattachhead"" align=""center"">[RESX:Delete]</td></tr>" & sOut & "</table>"
            End If
            Return tbl
        End Function

        Private Sub BindAttach(ByVal AttachIds As String)
            If UserId > 0 Then
                Dim sOut As String = String.Empty
                Dim lit As New Literal

                If AttachIds = String.Empty Then
                    Dim adb As New Data.AttachController
                    AttachIds = adb.GetAttachIds(AuthorId, ContentId)
                End If


                sOut = BuildAttachGrid(AttachIds)
                If PendingAttach >= ForumInfo.AttachCount Then
                    sOut &= "<script type=""text/javascript"">disableUpload();</script>"
                ElseIf cbAttach.IsCallback Then
                    sOut &= "<script type=""text/javascript"">enableUpload();</script>"
                End If
                If Not AttachIds = String.Empty Then
                    sOut &= "<script type=""text/javascript"">window.amaf_setAttachIds('" & AttachIds & "');</script>"
                End If
                lit.Text = sOut
                plhAttach.Controls.Add(lit)

            End If
        End Sub
        Private Sub BindMyFiles()
            If AuthorId > 0 Then
                Dim sOut As String = String.Empty
                Dim lit As New Literal
                sOut = BuildAttachGrid(ForumUser.UserId, String.Empty, 0, 300, "Filename", "ASC")
                sOut &= "<script type=""text/javascript"">window.amaf_myfileCount('" & PendingAttach & "');</script>"
                lit.Text = sOut
                plhMyFiles.Controls.Add(lit)
            End If
        End Sub

#End Region


    End Class
End Namespace
